<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #canvas {
        width: 90vw;
        height: 90vh;
      }
      body{
        padding:0;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
  </body>
  <script>
    var canvas = document.getElementById("canvas");
    var cxt = canvas.getContext("2d");

    cxt.strokeStyle = "red";

    var gravity = 0.98;
    var timer;
    var index = 0;
    var end = 550;
    var iStop = false;
    var ttop = 10;

    var blocks = [
      { left: 0, top: 0, end: 0, speed: 0, startIndex: 0 },
      // { left: 50, top: 0, end: 0, speed: 0, startIndex: 10 },
      // { left: 100, top: 0, end: 0, speed: 0, startIndex: 20 },
      // { left: 150, top: 0, end: 0, speed: 0, startIndex: 30 },
      // { left: 200, top: 0, end: 0, speed: 0, startIndex: 40 },
      // { left: 250, top: 0, end: 0, speed: 0, startIndex: 50 },
      // { left: 300, top: 0, end: 0, speed: 0, startIndex: 60 },
      // { left: 350, top: 0, end: 0, speed: 0, startIndex: 70 },
      // { left: 400, top: 0, end: 0, speed: 0, startIndex: 80 },
      // { left: 450, top: 0, end: 0, speed: 0, startIndex: 90 },
      // { left: 500, top: 0, end: 0, speed: 0, startIndex: 100 },
      // { left: 550, top: 0, end: 0, speed: 0, startIndex: 110 },
    ];

    function erase() {
      cxt.clearRect(0, 0, canvas.width, canvas.height);
    }

    function draw() {
      cxt.fillRect(0, ttop, 30, 10);
    }
    canvas.onclick = function (e) {
      var rect={x:10*4.5,y:ttop*4.6,w:10*4.5,h:30*4.5}
      //给canvas添加点击事件
      e = e || event; //获取事件对象
      //获取事件在canvas中发生的位置
      var x = e.clientX - canvas.offsetLeft;
      var y = e.clientY - canvas.offsetTop;
      console.log(x,y)
      console.log(rect)
      //如果事件位置在矩形区域中
      if (
        x >= rect.x &&
        x <= rect.x + rect.w &&
        y >= rect.y &&
        y <= rect.y + rect.h
      ) {
        console.log(1234)
      }
    };
    function animate() {
      erase();
      ttop = ttop + 0.98;
      draw();
      if (iStop) {
        cancelRequestAnimationFrame(timer);
      } else {
        timer = requestAnimationFrame(animate);
      }
    }

    animate();
  </script>
</html>
